Object.defineProperty(exports, "__esModule", { value: true });
exports.Typewriter = void 0;
// 打字机队列
var Typewriter = /** @class */ (function () {
  function Typewriter(onConsume) {
    this.onConsume = onConsume;
    this.queue = [];
    this.consuming = false;
  }
  // 输出速度动态控制
  Typewriter.prototype.dynamicSpeed = function () {
    var speed = 2000 / this.queue.length;
    if (speed > 200) {
      return 200;
    } else {
      return speed;
    }
  };
  // 添加字符串到队列
  Typewriter.prototype.add = function (str) {
    var _a;
    if (!str) return;
    (_a = this.queue).push.apply(_a, str.split(""));
  };
  // 消费
  Typewriter.prototype.consume = function () {
    if (this.queue.length > 0) {
      var str = this.queue.shift();
      str && this.onConsume(str);
    }
  };
  // 消费下一个
  Typewriter.prototype.next = function () {
    var _this = this;
    this.consume();
    // 根据队列中字符的数量来设置消耗每一帧的速度，用定时器消耗
    this.timmer = setTimeout(function () {
      _this.consume();
      if (_this.consuming) {
        _this.next();
      }
    }, this.dynamicSpeed());
  };
  // 开始消费队列
  Typewriter.prototype.start = function () {
    this.consuming = true;
    this.next();
  };
  // 结束消费队列
  Typewriter.prototype.done = function () {
    this.consuming = false;
    clearTimeout(this.timmer);
    // 把queue中剩下的字符一次性消费
    this.onConsume(this.queue.join(""));
    this.queue = [];
  };
  return Typewriter;
})();
exports.Typewriter = Typewriter;
